package it.tukano.treditor.ui;

import it.tukano.collections.LinkedListExt;
import it.tukano.collections.ListExt;
import it.tukano.fun.VFunction1;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.event.InputAdapter;
import it.tukano.swingdeco.event.MouseEventExt;
import it.tukano.swingdeco.input.ColorBox;
import it.tukano.swingdeco.input.PopupColorChooser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Point;

public class ColorEditor extends JPanelExt {
    
    /* default serial version uid*/
    private static final long serialVersionUID = 0;
    
    private final ListExt<Runnable> listeners = new LinkedListExt<>();
    private final ColorBox box = new ColorBox(50, 25);
    private final PopupColorChooser colorChooser = new PopupColorChooser();
    private Color editedColor;

    /**
     * Instance initializer
     */
    public ColorEditor() {
        super(new BorderLayout());
        add(box, BorderLayout.CENTER);
        box.addMouseListener(new InputAdapter() {

            @Override
            protected void onLeftMouseClicked(MouseEventExt e) {
                popupColorChooser();
            }
        });
    }
    
    public void popupColorChooser() {
        colorChooser.popup(box, new Point(0,0), editedColor, new VFunction1<Color>() {

            @Override
            protected void doApply(Color p) {
                editedColor = p;
                box.setForeground(p);
                for (Runnable runnable : listeners) {
                    runnable.run();
                }
            }
        });
    }
    
    public void setEditedValue(Color c) {
        editedColor = c;
        box.setForeground(c);
    }
    
    public Color getEditedValue() {
        return editedColor;
    }
    
    public void addListener(Runnable r) {
        listeners.add(r);
    }
}
